﻿using Microsoft.Extensions.Options;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MiniPc.API.MongoCRUD
{
    //MongoDB的配置类
    public class MongoConfig
    {
        //客户端链接字符串
        public string MongoClient { get; set; }
        //数据库名称
        public string GetDatabase { get; set; }
        //集合名称
        public string GetCollection { get; set; }
    }


    /// <summary>
    /// MongoDB增删改查
    /// </summary>
    public class MongoCRUD<T>
    {
        // 对名为 T 的集合进行增删改查

        private readonly IMongoCollection<T> _mongoCollection;


        #region MongoDB链接字符串
        /// <summary>
        /// 获取Appsetting中的链接字符串配置
        /// </summary>
        private readonly IOptions<MongoConfig> _options;
        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="options"></param>
        public MongoCRUD(IOptions<MongoConfig> options)
        {
            _options = options;

            // 使用连接字符串连接 mongodb 服务器
            var client = new MongoClient($"mongodb://{_options.Value.MongoClient}:27017");
            // 获取名为 BookstoreDb 的数据库
            var database = client.GetDatabase($"{_options.Value.GetDatabase}");
            // 获取名为 Books 的集合
            _mongoCollection = database.GetCollection<T>($"{_options.Value.GetCollection}");
        }
        #endregion


        /// <summary>
        /// 显示
        /// </summary>
        /// <returns></returns>
        public List<T> Get()
        {
            return _mongoCollection.Find(Entity => true).ToList();
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="conn"></param>
        /// <returns></returns>
        public List<T> GetOne(System.Linq.Expressions.Expression<Func<T, bool>> conn)
        {
            return _mongoCollection.Find(conn).ToList();
        }


        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="Entity"></param>
        /// <returns></returns>
        public T Create(T Entity)
        {
            _mongoCollection.InsertOne(Entity);
            return Entity;
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="Entity"></param>
        public void Update(System.Linq.Expressions.Expression<Func<T, bool>> conn, T Entity)
        {
            _mongoCollection.ReplaceOne(conn, Entity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="conn"></param>
        public void Remove(System.Linq.Expressions.Expression<Func<T, bool>> conn)
        {
            _mongoCollection.DeleteOne(conn);
        }
    }

}
